import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author 残月
 */
public class SocketClient {

    public void client() throws IOException {

        Socket socket = new Socket("localhost", 8900);

        byte[] bytes = new byte[1024];
        Scanner scanner = new Scanner(System.in);
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    int read = in.read(bytes);
                    String list = new String(bytes, 0, read, Charset.defaultCharset());
                    System.out.println("服务器: " + list);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }, 0, 500);

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    out.write(scanner.next().getBytes(StandardCharsets.UTF_8));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }, 0, 500);
    }

    public static void main(String[] args) throws IOException {
        SocketClient socketClient = new SocketClient();
        socketClient.client();


    }

}
